package club.twelveblog.tblog.controller;

import club.twelveblog.tblog.common.constants.HttpStatusConstants;
import club.twelveblog.tblog.common.dto.Result;
import club.twelveblog.tblog.common.dto.UserDto;
import club.twelveblog.tblog.common.dto.userResult;
import club.twelveblog.tblog.common.enums.ExceptionEnum;
import club.twelveblog.tblog.common.exception.BlogException;
import club.twelveblog.tblog.entity.User;
import club.twelveblog.tblog.service.UserService;
import club.twelveblog.tblog.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/tblog")
public class CommonController {
    @Autowired
    private ValidateCode validateCode;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private Token token;
    @Autowired
    private userResult userresult;
    @Autowired
    private UserService userService;
    @Autowired
    private changeDate changDate;
    @Autowired
    private Defence defence;
    private Cookie cookie;
    /**
     * 注册
     */
    @PostMapping(value = "/register")
    public Result userRegister(@RequestBody User user
    ) {
        User user2=defence.defenceInjection(user);
        boolean re=userService.isExist(user2.getUsername());
        if (user2.getUsername()!=""&user2.getPassword()!=""){
            if(re!=true){
                User user1=new User();
                user1.setUsername(user2.getUsername());
//            String md5Password = DigestUtils.md5DigestAsHex(user.getUsername().getBytes());
                user1.setPassword(user2.getPassword());
                user1.setSex(user2.getSex());
                user1.setEmail(user2.getEmail());
                user1.setAddress(user2.getAddress());
                user1.setBirthday(user2.getBirthday());
                userService.userRegister(user1);
                return ResultGenerator.getResultByHttpNoData(HttpStatusConstants.REGISTER_SUCCESS);
            }else {
                throw new BlogException(ExceptionEnum.REGISTER_FAILED);
            }
        }else {
            return ResultGenerator.getResultByHttp(HttpStatusConstants.SUCCESS,"请输入正确的账号和密码");
        }

    }

    /**
     * 用户登录
     */
    @PostMapping("/login")

    public Result<User> isExistUser(@RequestBody UserDto userDto,
                                    @CookieValue ("verify") String verify,
                                    HttpServletResponse response) {
//        boolean num =userService.isExist(username);
        System.out.println(userDto.getUsername());
        System.out.println(userDto.getPassword());
        System.out.println(userDto.getCheckCode());
        //检测用户状态
        boolean islock=userService.islock(userDto.getUsername());
        User user1=userService.login(userDto.getUsername(),userDto.getPassword());
        //根据cookie里面的verify来获取验证码
        String checkcode= (String) redisTemplate.opsForValue().get(verify);
        redisTemplate.delete(verify);
        if (islock!=true){
            if(userDto.getCheckCode().equalsIgnoreCase(checkcode)){
                if (null!=user1){
                    user1.setPassword(null);
                    //生成token
                    String a=token.getToken(32);
                    //向redis里面存数据
                    redisTemplate.opsForValue().set(a,user1.getUser_id());
                    //设置返回数据
                    userresult.setUser_id(user1.getUser_id());
                    userresult.setAddress(user1.getAddress());
                    userresult.setAuthorImg(user1.getAuthorImg());
                    userresult.setBirthday(user1.getBirthday());
                    userresult.setEmail(user1.getEmail());
                    userresult.setIntroduction(user1.getIntroduction());
                    //把token添加到cookie返回给客户端

                    cookie=new Cookie("token",a);
                    cookie.setHttpOnly(true);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                    return ResultGenerator.getResultByHttp(HttpStatusConstants.LOGIN_SUCCESS,userresult);
                }
                else {
                    throw new BlogException(ExceptionEnum.LOGIN_PASSWORD_FAILED);
                }
            }else {
                return ResultGenerator.getResultByHttp(HttpStatusConstants.SUCCESS,"验证码错误,请重新获取");
            }
        }else {
            return  ResultGenerator.getResultByHttp(HttpStatusConstants.SUCCESS,"账号已被锁定");
        }




    }

    /**
     * 用户注销模块
     */
    @GetMapping("/logout")
    public Result<String> loginOut(HttpServletResponse response, @CookieValue("token") String token){

        System.out.println(token);

        cookie.setValue("zhuxiao");

        response.addCookie(cookie);
        redisTemplate.delete(token);
        return ResultGenerator.getResultByHttp(HttpStatusConstants.SUCCESS,"注销成功");
    }
    /**
     * 验证码接口
     *
     */
    @GetMapping(value = "/getCheckCode",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Result<String> code(HttpServletResponse response){
        String[] a=validateCode.getRandomCodeBase64();
        String code=a[0];
        String url=a[1];
        String verify=token.getToken(10);
        //向redis缓存存入验证码和验证字符串
        redisTemplate.opsForValue().set(verify,code);
        //将verify_id添加到cookie
        cookie=new Cookie("verify",verify);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        response.addCookie(cookie);
        return ResultGenerator.getResultByHttp(HttpStatusConstants.SUCCESS,"data:image/jpg;base64,"+url);
    }
}
